package com.adlotto2.lcdns.activity.notify;

import java.util.ArrayList;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.adlotto2.lcdns.R;
import com.adlotto2.lcdns.activity.notify.adapter.LottoAdPartnerAdapter;
import com.adlotto2.lcdns.common.BaseActivity;
import com.adlotto2.lcdns.cronos.data.CNLottoAdPartnerData;
import com.adlotto2.lcdns.cronos.datahandler.CNBaseDataParser;
import com.adlotto2.lcdns.cronos.datahandler.CNBaseDataSet;
import com.adlotto2.lcdns.cronos.datahandler.CNResultSet;
import com.adlotto2.lcdns.cronos.http.CNLottoAdApiSetEx;
import com.adlotto2.lcdns.cronos.parser.CNPartnerListParser;
import com.adlotto2.lcdns.util.ApplicationUtils;
import com.adlotto2.lcdns.util.CNCronosLog;
import com.adlotto2.lcdns.util.LottoAdConstants;
import com.adlotto2.lcdns.util.UnbindHelper;

/**
 * 공지사항 - 제휴회사 Activity
 * @author Administrator
 *
 */
public class LottoAdPartnerListActivity extends BaseActivity{
	
	private Context mContext;
	
	/**카카오톡 친구추천 버튼*/
	private Button mKakaoBtn;
	/**제휴회사 섬네일 GridView**/
	private GridView mPartnerGrid;
	/** 목록 없을시 텍스트뷰 **/
	private TextView mEmptyListTv;
	/**제휴회사 섬네일 Grid Adapter**/
	private LottoAdPartnerAdapter mGridAdapter;
	/**제휴회사 섬네일 DataSetList**/
	private ArrayList<CNBaseDataSet> mDataSetList =  new ArrayList<CNBaseDataSet>();;
	
	/** 요청 페이지 Number **/
	private int mPageNum = 1;
	/** 데이터 셋 유/무 체크 플래그 **/
	private boolean isDataSet = false;
	/** 다음페이지 유/무 체크 플래그 **/
	private boolean isNextPage = false;
	/** 비동기 작업수행 여부 체크 플래그 **/
	private boolean mNetAsyncing = false;
	/** 리스트의 마지막 포지션값 **/
	private int mListLastPosition = 0;
	
	@Override
	protected int onGetContentViewResource() {
		return R.layout.lottoad_menu_notify_partner_list;
	}

	@Override
	protected void onInit() {
		buildComponnent();
	}
	
	private void buildComponnent(){
		this.mContext = this;
		
		mKakaoBtn = (Button) findViewById(R.id.button_kakao);
		mPartnerGrid = (GridView) findViewById(R.id.gridView_partner);
		mEmptyListTv = (TextView) findViewById(R.id.list_empty);
		mGridAdapter = new LottoAdPartnerAdapter(mContext);
		mGridAdapter.setDataSetList(mDataSetList);
		mPartnerGrid.setAdapter(mGridAdapter);
		
		onRequestData();
		
		mPartnerGrid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
				
			}
		});
		
		mPartnerGrid.setOnScrollListener(new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView abslistview, int i) {
				try
		        { 
					if(isDataSet)
					{
						int mLastPosition = abslistview.getLastVisiblePosition();
						CNCronosLog.d("mLastPosition : "+ mLastPosition);
						if((mLastPosition == mListLastPosition - 1) && isNextPage && !mNetAsyncing){ 
							mPageNum = mPageNum + 1;
			            	mNetAsyncing = true;
			            	onRequestData();
			            }
					}
		        }catch(Exception e){ 
		        	
		        }
			}
			
			@Override
			public void onScroll(AbsListView abslistview, int i, int j, int k) {
				
			}
		});
		
		mKakaoBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ApplicationUtils.checkPackage(mContext, LottoAdConstants.KAKAO_PACKAGE_NAME);
			}
		});
	}
	
	@Override
	public String onGetAsyncRequestUrl() {
		CNCronosLog.d("onGetAsyncRequestUrl()");
		String url = null;
		
		CNLottoAdApiSetEx MnetGlobalApiSetEx = CNLottoAdApiSetEx.getInstance();
		url = MnetGlobalApiSetEx.getPartnerListUrl(mContext, mPageNum, 8);
		
		CNCronosLog.d("onGetAsyncRequestUrl", "url : "+url);
		
		return url;
	}
	
	@Override
	public void onAsyncCancelRequest() 
	{
		super.hideLoadingDialog();
		CNCronosLog.d("onAsyncCancelRequest()");
	}

	@Override
	public void onAsyncDataError(Element xmlObject, String errorMessage)
	{
		super.hideLoadingDialog();
		
		NodeList rcodeNode = xmlObject.getElementsByTagName("rcode");
		String rcode = rcodeNode.item(0).getFirstChild().getNodeValue();
		
		if(!"RET0002".equals(rcode)){
			ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.popup_alert), errorMessage);
		} else {
			updateUI(rcode);
		}
	}

	@Override
	public void onAsyncPreRequest()
	{
		super.showLoadingDialog();
	}

	@Override
	public void onAsyncRequestCompleted(Element xmlObject)
	{
		super.hideLoadingDialog();
			
		try {
			parsePartnerList(xmlObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 제휴회사 섬네일 파싱
	 * @param xmlObject
	 * @throws Exception
	 */
	private void parsePartnerList(Element xmlObject) throws Exception
	{
		
		String Tag = "parsePartnerList";
		
		CNBaseDataParser parser = new CNPartnerListParser();
		CNResultSet resultSet = parser.parse(xmlObject);
		ArrayList<CNBaseDataSet> dataSet = null;
		
		if (resultSet != null)
		{
			dataSet = resultSet.getDataSetList();
			if (dataSet != null)
			{
				int count = dataSet.size();		
				CNCronosLog.d(Tag, "DataSet.size():" + count);
				for (int i = 0; i < count; i++)
				{
					CNLottoAdPartnerData data = (CNLottoAdPartnerData) dataSet.get(i);
					
					System.out.print("============ " + i + " ============");
					System.out.print("partnerImg:" + data.partnerImg);
					
					mDataSetList.add(data);
				}
			} 
			
			isNextPage = mDataSetList.size() < resultSet.getTotalCount();
			isDataSet = mDataSetList.size() > 0;
			mListLastPosition =  mDataSetList.size();
		}
		
		mGridAdapter.notifyDataSetChanged();
		mNetAsyncing = false;
		
		updateUI(resultSet.getRcode());
	}
	
	private void updateUI(String rcode){
		if("RET0000".equals(rcode)){
			mPartnerGrid.setVisibility(View.VISIBLE);
			mEmptyListTv.setVisibility(View.GONE);
		} else if("RET0002".equals(rcode)){
			mPartnerGrid.setVisibility(View.GONE);
			mEmptyListTv.setVisibility(View.VISIBLE);
		}
	}
	
	@Override
	public void onAsyncRequestError(int errorNumber) {
		super.hideLoadingDialog();
		
		ApplicationUtils.showOkDialog(mContext,0,getString(R.string.popup_alert), ApplicationUtils.getErrorMessage(mContext, errorNumber));
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		mGridAdapter.recycle();
		System.gc();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		UnbindHelper.unbindReferences(getWindow().getDecorView().getRootView());
		System.gc();
	}
}
